﻿using System;
using System.Windows.Forms;
using Xilium.CefGlue;

namespace CefWinform.BS
{
    public class BsCtl
    {
        private CefBrowser bs;
        private Control parent;
        public BsCtl(Control ctl, string url)
        {
            this.parent = ctl;
            CefWindowInfo cwi = CefWindowInfo.Create();
            cwi.SetAsChild(this.parent.Handle, new CefRectangle(0, 0, this.parent.Width, this.parent.Height));
            BsClient bc = new BsClient();
            bc.OnCreated += new EventHandler(this.bc_OnCreated);
            CefBrowserSettings bs = new CefBrowserSettings();
            CefBrowserHost.CreateBrowser(cwi, bc, bs, url);
            this.parent.SizeChanged += new EventHandler(this.parent_SizeChanged);
        }
        private void bc_OnCreated(object sender, EventArgs e)
        {
            this.bs = (CefBrowser)sender;
            IntPtr handle = this.bs.GetHost().GetWindowHandle();
            this.ResizeWindow(handle, this.parent.Width, this.parent.Height);
        }
        private void parent_SizeChanged(object sender, EventArgs e)
        {
            if (this.bs != null)
            {
                IntPtr handle = this.bs.GetHost().GetWindowHandle();
                this.ResizeWindow(handle, this.parent.Width, this.parent.Height);
            }
        }
        private void ResizeWindow(IntPtr handle, int width, int height)
        {
            if (handle != IntPtr.Zero)
            {
                NativeMethod.SetWindowPos(handle, IntPtr.Zero, 0, 0, width, height, 6u);
            }
        }
        public void LoadUrl(string url)
        {
            this.bs.GetMainFrame().LoadUrl(url);
        } 
    }
}